package jhunter.template;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import jhunter.common.exception.ConfigException;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

public class TemplateLoader {

	private static VelocityEngine engine = new VelocityEngine(); 
	
	static {
		engine.addProperty(Velocity.RESOURCE_LOADER, "classpath");
		engine.addProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
		engine.init();
	}

	public static String getStringByTemplate(String templateFilePath, Map<String, Object> values) {
		VelocityContext context = new VelocityContext();
		if (values != null) {
			for (String key : values.keySet()) {
				context.put(key, values.get(key));
			}
		}
		Template tp = engine.getTemplate(templateFilePath, "utf-8");
		StringWriter writer = new StringWriter();
		tp.merge(context, writer);
		return writer.toString();
	}
	
	public static void renderByTemplate(HttpServletResponse response ,String templateFilePath, Map<String, Object> values)  {
		VelocityContext context = new VelocityContext();
		if (values != null) {
			for (String key : values.keySet()) {
				context.put(key, values.get(key));
			}
		}
		Template tp = engine.getTemplate(templateFilePath,"utf-8");
		try {
			tp.merge(context, response.getWriter());
		} catch (ResourceNotFoundException e) {
			e.printStackTrace();
			throw new ConfigException(e);
		} catch (ParseErrorException e) {
			e.printStackTrace();
			throw new ConfigException(e);
		} catch (MethodInvocationException e) {
			e.printStackTrace();
			throw new ConfigException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new ConfigException(e);
		}
	}

}
